package com.fh.fruit.controller.user;

import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fh.controller.base.BaseController;
import com.fh.entity.Page;
import com.fh.fruit.service.user.FruitUserManager;
import com.fh.service.system.menu.MenuManager;
import com.fh.service.system.role.RoleManager;
import com.fh.util.AppUtil;
import com.fh.util.DateUtil;
import com.fh.util.Jurisdiction;
import com.fh.util.ObjectExcelView;
import com.fh.util.PageData;
import com.fruit.pojo.user.UserLogin;
import com.fruit.service.user.UserManager;
import com.fruit.util.ResultInfo;

@Controller
@RequestMapping(value="/fruitUser")
public class FarmUserController extends BaseController {

	String menuUrl = "fruitUser/listFruitUsers"; //菜单地址(权限用)
	
	@Resource(name="fruitUserService")
	private FruitUserManager fruitUserService;
	@Resource(name="roleService")
	private RoleManager roleService;
	@Resource(name="menuService")
	private MenuManager menuService;
	
	@Autowired
    private UserManager userService;
	
	/**显示会员统计列表
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/listFruitUsers")
	public ModelAndView listUsers(Page page)throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		String endTime=pd.getString("endTime");
		pd.put("time", DateUtil.getTime());
		pd.put("afterTime", DateUtil.getAfterDayDate("60"));
		String age=pd.getString("age");
		if(age != null && !"".equals(age)){
			pd.put("year1", DateUtil.getAfterYear("-30"));
			pd.put("year2", DateUtil.getAfterYear("-50"));
		}
		page.setPd(pd);
		//int num=fruitUserService.getRegisterNum(pd);
		List<Map<String,Object>> fruitUserList = fruitUserService.listfruitUsers(page);	//列出用户列表
		pd.put("num", page.getTotalResult());
		pd.put("endTime", endTime);
		mv.setViewName("farm/user/User_list");
		mv.addObject("fruitUserList", fruitUserList);
		mv.addObject("pd", pd);
		mv.addObject("QX",Jurisdiction.getHC());	//按钮权限
		return mv;
	}
	
	/**导出用户注册信息到EXCEL
	 * @return
	 */
	@RequestMapping(value="/excel")
	public ModelAndView exportExcel(Page page){
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		String time=DateUtil.getTime();
		String afterTime=DateUtil.getAfterDayDate("60");
		try{
			if(Jurisdiction.buttonJurisdiction(menuUrl, "cha")){
				
				Map<String,Object> dataMap = new HashMap<String,Object>();
				List<String> titles = new ArrayList<String>();
				titles.add("UID"); 		//1
				titles.add("昵称");  		//2
				titles.add("手机号");			//3
				titles.add("消费金额");			//4
				titles.add("性别/认证性别");			//5
				titles.add("认证地区");			//6
				titles.add("认证年龄");		//7
				titles.add("注册来源");	//8
				titles.add("权益周期");//9
				titles.add("注册日期");//10
				dataMap.put("titles", titles);
				page.setShowCount(Integer.parseInt(pd.getString("showCount")));
				page.setCurrentPage(Integer.parseInt(pd.getString("pageNum")));
				page.setPd(pd);
				List<Map<String,Object>> fruitUserList = fruitUserService.listfruitUsers(page);
				List<PageData> varList = new ArrayList<PageData>();
				for(int i=0;i<fruitUserList.size();i++){
					PageData vpd = new PageData();
					String sex=(String)fruitUserList.get(i).get("sex");
					String rsex=(String)fruitUserList.get(i).get("rsex");
					BigDecimal money=(BigDecimal)fruitUserList.get(i).get("money");
					String birthday=(String)fruitUserList.get(i).get("birthday");
					String city=(String)fruitUserList.get(i).get("city");
					String country=(String)fruitUserList.get(i).get("country");
					String end_use_time=(String)fruitUserList.get(i).get("end_use_time");
					int ageNum=0;
					String moneys=null;
					if(sex != null && !"".equals(sex)){
						if(sex =="01"){
							sex="男";
						} else if(sex =="00"){
							sex="女";
						}else {
							sex="保密";
						}
					} else{
						sex="保密";
					}
					if(rsex != null && !"".equals(rsex)){
						if(rsex =="01"){
							rsex="男";
						} else {
							rsex="女";
						}
					}else{
						rsex="未认证";
					}
					if(money == null || "".equals(money)) {
						moneys="未消费";
					}else{
						moneys=money.toString();
					}
					if(birthday!=null && !"".equals(birthday)){
						ageNum=DateUtil.getAgeByBirthDay(birthday);
					} 
					String region=null;
					if(city==null || "".equals(city)){
						region="未认证";
					} else {
						region=city+" "+country;
					}
					if(end_use_time != null && !"".equals(end_use_time)){
						Date endTime= DateUtil.fomatDate1(end_use_time);
						Date times= DateUtil.fomatDate1(time);
						Date afterTimes= DateUtil.fomatDate1(afterTime);
						if(endTime.getTime()<times.getTime()){
							end_use_time="权益期外";
						}
						if(afterTimes.getTime()<endTime.getTime()){
							end_use_time="未过期";
						}
						if(afterTimes.getTime()>endTime.getTime() && endTime.getTime()>times.getTime()){
							end_use_time="二个月内过期";
						}
					} else {
						end_use_time="未消费";
					}
					
					vpd.put("var1", (Integer)fruitUserList.get(i).get("id"));		//1
					vpd.put("var2", (String)fruitUserList.get(i).get("petName"));		//2
					vpd.put("var3", (String)fruitUserList.get(i).get("phone"));			//3
					vpd.put("var4", moneys);	//4
					vpd.put("var5", sex+"/"+rsex);		//5
					vpd.put("var6", region);		//6
					vpd.put("var7", ageNum==0?"未认证":ageNum);	//7
					vpd.put("var8", (String)fruitUserList.get(i).get("channel"));			//8
					vpd.put("var9", end_use_time);			//9
					vpd.put("var10", (String)fruitUserList.get(i).get("creation_date"));			//10
					varList.add(vpd);
				}
				dataMap.put("varList", varList);
				ObjectExcelView erv = new ObjectExcelView();					//执行excel操作
				mv = new ModelAndView(erv,dataMap);
			}
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
	}
	
	/**显示会员消费统计列表
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/listConsumeUsers")
	public ModelAndView listConsumeUsers(Page page)throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		String endTime=pd.getString("endTime");
		pd.put("time", DateUtil.getTime());
		pd.put("afterTime", DateUtil.getAfterDayDate("60"));
		page.setPd(pd);
		//int num=fruitUserService.getConsumeNum(pd);
		List<Map<String,Object>> fruitUserList = fruitUserService.listConsumeUsers(page);
		pd.put("num", page.getTotalResult());
		pd.put("endTime", endTime);
		mv.setViewName("farm/user/User_consume_list");
		mv.addObject("fruitUserList", fruitUserList);
		mv.addObject("pd", pd);
		mv.addObject("QX",Jurisdiction.getHC());	//按钮权限
		return mv;
	}
	
	/**导出用户消费信息到EXCEL
	 * @return
	 */
	@RequestMapping(value="/consumeExcel")
	public ModelAndView consumeExcel(Page page){
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		String time=DateUtil.getTime();
		String afterTime=DateUtil.getAfterDayDate("60");
		try{
			if(Jurisdiction.buttonJurisdiction(menuUrl, "cha")){
				
				Map<String,Object> dataMap = new HashMap<String,Object>();
				List<String> titles = new ArrayList<String>();
				titles.add("UID"); 		//1
				titles.add("昵称");  		//2
				titles.add("手机号");			//3
				titles.add("消费金额");			//4
				titles.add("购买商品数");			//5
				titles.add("权益周期");//6
				titles.add("注册日期");//7
				titles.add("最近一次消费时间");//8
				dataMap.put("titles", titles);
				page.setShowCount(Integer.parseInt(pd.getString("showCount")));
				page.setCurrentPage(Integer.parseInt(pd.getString("pageNum")));
				page.setPd(pd);
				List<Map<String,Object>> fruitUserList = fruitUserService.listConsumeUsers(page);
				List<PageData> varList = new ArrayList<PageData>();
				for(int i=0;i<fruitUserList.size();i++){
					PageData vpd = new PageData();
					String end_use_time=(String)fruitUserList.get(i).get("end_use_time");
					BigDecimal real_price=(BigDecimal)fruitUserList.get(i).get("real_price");
					String moneys=null;
					if(end_use_time != null && !"".equals(end_use_time)){
						Date endTime= DateUtil.fomatDate1(end_use_time);
						Date times= DateUtil.fomatDate1(time);
						Date afterTimes= DateUtil.fomatDate1(afterTime);
						if(endTime.getTime()<times.getTime()){
							end_use_time="权益期外";
						}
						if(afterTimes.getTime()<endTime.getTime()){
							end_use_time="未过期";
						}
						if(afterTimes.getTime()>endTime.getTime() && endTime.getTime()>times.getTime()){
							end_use_time="二个月内过期";
						}
					} else {
						end_use_time="未消费";
					}
					if(real_price == null || "".equals(real_price)) {
						moneys="未消费";
					}else{
						moneys=real_price.toString();
					}
					vpd.put("var1", (Integer)fruitUserList.get(i).get("user_id"));		//1
					vpd.put("var2", (String)fruitUserList.get(i).get("petName"));		//2
					vpd.put("var3", (String)fruitUserList.get(i).get("phone"));			//3
					vpd.put("var4", moneys);	//4
					vpd.put("var5", (Long)fruitUserList.get(i).get("goodsNum")+" 件");		//5
					vpd.put("var6", end_use_time);		//6
					vpd.put("var7", (String)fruitUserList.get(i).get("creation_date"));	//7
					vpd.put("var8", (String)fruitUserList.get(i).get("newTime"));			//8
					varList.add(vpd);
				}
				dataMap.put("varList", varList);
				ObjectExcelView erv = new ObjectExcelView();					//执行excel操作
				mv = new ModelAndView(erv,dataMap);
			}
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
	}
	
	/**获取用户信息
	 * @return ModelAndView
	 * @throws Exception
	 */
	@RequestMapping(value="/details")
	public ModelAndView details()throws Exception{
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "cha")){return null;} //校验权限
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		Map<String,Object> user=fruitUserService.getUserDetails(pd);
		mv.addObject("user",user);
		mv.setViewName("farm/user/user-detail");
		mv.addObject("pd", pd);
		mv.addObject("QX",Jurisdiction.getHC());	//按钮权限
		return mv;
	}
	/**获取用户信息
	 * @return ModelAndView
	 * @throws Exception
	 */
	@RequestMapping(value="/basic")
	public ModelAndView basic()throws Exception{
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "cha")){return null;} //校验权限
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		Map<String,Object> user=fruitUserService.getUserDetails(pd);
		String birthday=(String)user.get("birthday");
		user.put("age", DateUtil.getAgeByBirthDay(birthday));
		mv.addObject("user",user);
		mv.setViewName("farm/user/user-basic-info");
		mv.addObject("pd", pd);
		mv.addObject("QX",Jurisdiction.getHC());	//按钮权限
		return mv;
	}
	
	/**获取用户购买信息
	 * @return ModelAndView
	 * @throws Exception
	 */
	@RequestMapping(value="/buyInfo")
	public ModelAndView buyInfo()throws Exception{
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "cha")){return null;} //校验权限
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		List<Map<String,Object>> user=fruitUserService.getBuyInfo(pd);
		int num=0;
		BigDecimal price=new BigDecimal("0");
		for (Map<String, Object> map : user) {
			num+=(int)map.get("number");
			price=price.add((BigDecimal)map.get("real_price")); 
		}
		pd.put("num",num);
		pd.put("price",price);
		mv.addObject("user",user);
		mv.setViewName("farm/user/buy-info");
		mv.addObject("pd", pd);
		mv.addObject("QX",Jurisdiction.getHC());	//按钮权限
		return mv;
	}
	
	/**获取用户邀请信息
	 * @return ModelAndView
	 * @throws Exception
	 */
	@RequestMapping(value="/inviteInfo")
	public ModelAndView inviteInfo()throws Exception{
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "cha")){return null;} //校验权限
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		Map<String,Object> user=fruitUserService.getInviteInfo(pd);
		if(user != null){
			String end_use_time=(String)user.get("end_use_time");
			if(end_use_time !=null && !"".equals(end_use_time)){
				String time=DateUtil.getTime();
				if(time.compareTo(end_use_time)>0){
					user.put("state", "01");
				} 
			}else {
				user.put("state", "02");
			}
		}
		mv.addObject("user",user);
		mv.setViewName("farm/user/invite-info");
		mv.addObject("pd", pd);
		mv.addObject("QX",Jurisdiction.getHC());	//按钮权限
		return mv;
	}
	
	/**获取用户邀请信息
	 * @return ModelAndView
	 * @throws Exception
	 */
	@RequestMapping(value="/inviteNum")
	public ModelAndView inviteNum()throws Exception{
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "cha")){return null;} //校验权限
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		Map<String,Object> user=fruitUserService.getUserDetails(pd);
		List<Map<String,Object>> inviteNum= fruitUserService.getInviteNum(pd);
		mv.addObject("inviteNum",inviteNum);
		mv.addObject("user",user);
		if(inviteNum != null){
			mv.addObject("num",inviteNum.size());
		}
		mv.setViewName("farm/user/invite_num");
		mv.addObject("pd", pd);
		mv.addObject("QX",Jurisdiction.getHC());	//按钮权限
		return mv;
	}
	
	
	/**获取用户信息
	 * @return ModelAndView
	 * @throws Exception
	 */
	@RequestMapping(value="/wholeDetails")
	public ModelAndView wholeDetails()throws Exception{
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "cha")){return null;} //校验权限
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		String times=pd.getString("times");
		if(times != null && !"".equals(times)){
			if("1".equals(times)){
				pd.put("startTime", DateUtil.getDay());
				pd.put("endTime", DateUtil.getTime());
			} else if("2".equals(times)){
				pd.put("startTime", DateUtil.getAfterDayDates("-1"));
				pd.put("endTime", DateUtil.getAfterDayDates("-1"));
			} else if("3".equals(times)){
				pd.put("startTime", DateUtil.getAfterDayDates("-2"));
				pd.put("endTime", DateUtil.getAfterDayDates("-2"));
			} else if("4".equals(times)){
				pd.put("startTime", DateUtil.getAfterDayDates("-7"));
				pd.put("endTime", DateUtil.getTime());
			} else if("5".equals(times)){
				pd.put("startTime", DateUtil.getAfterDayDates("-30"));
				pd.put("endTime", DateUtil.getTime());
			}
		}
		String endTime =pd.getString("endTime");
		String year1=DateUtil.getAfterYears("-30");
		String year2=DateUtil.getAfterYears("-50");
		pd.put("year1", year1);
		pd.put("year2", year2);
		Map<String,Object> user=fruitUserService.getWholeDetails(pd);
		Map<String,Object> info=fruitUserService.getUserAge(pd);
		List<Map<String,Object>> infos =fruitUserService.getUserRegion(pd);
		Map<String,Object> ratio=fruitUserService.getRatio(pd);
		int num=0;
		if(infos!= null){
			for (Map<String, Object> map : infos) {
				Long nums=(Long)map.get("num");
				 num+=nums.intValue();
				
			}
		}
		pd.put("endTime", endTime);
		mv.addObject("user",user);
		mv.addObject("info",info);
		mv.addObject("infos",infos);
		mv.addObject("num",num);
		mv.addObject("ratio",ratio);
		mv.setViewName("farm/user/user_whole");
		mv.addObject("pd", pd);
		mv.addObject("QX",Jurisdiction.getHC());	//按钮权限
		return mv;
	}
	

	
	/**去新增用户页面
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/goAddUser")
	public ModelAndView goAddUser()throws Exception{
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "add")){return null;} //校验权限
		ModelAndView mv = this.getModelAndView();
		mv.setViewName("system/listfruitUsers/listfruitUsers_add");
		return mv;
	}
	
	/**新增用户
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/saveUser")
	public ModelAndView saveU(HttpServletRequest requset) throws Exception{
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "add")){return null;} //校验权限
		logBefore(logger, Jurisdiction.getUsername()+"新增用户");
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData(); 
		fruitUserService.saveUser(pd);
		mv.setViewName("save_result");
		return mv;
	}
	
	
	/**删除用户
	 * @param out
	 * @throws Exception 
	*/
	@RequestMapping(value="/deleteU")
	public void deleteU(PrintWriter out) throws Exception{
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "del")){return;} //校验权限
		logBefore(logger, Jurisdiction.getUsername()+"删除会员");
		PageData pd = new PageData();
		pd = this.getPageData();
		fruitUserService.updateUserState(pd);
		out.write("success");
		out.close();
	}
	/**批量删除
	 * @return
	*/
	@RequestMapping(value="/deleteAllU")
	@ResponseBody
	public Object deleteAllU() {
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "del")){} //校验权限
		logBefore(logger, Jurisdiction.getUsername()+"批量删除会员");
		PageData pd = new PageData();
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			pd = this.getPageData();
			List<PageData> pdList = new ArrayList<PageData>();
			String USER_ID = pd.getString("USER_IDS");
			if(null != USER_ID && !"".equals(USER_ID)){
				String ArrayUSER_IDS[] = USER_ID.split(",");
				for (int i = 0; i < ArrayUSER_IDS.length; i++) {
					String str = ArrayUSER_IDS[i];
					pd.put("ID", str);
					pd.put("state", "02");
					fruitUserService.updateUserState(pd);
				}
				pd.put("msg", "ok");
			}else{
				pd.put("msg", "no");
			}
			pdList.add(pd);
			map.put("list", pdList);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			logAfter(logger);
		}
		return AppUtil.returnObject(pd, map);
	}
	
	/**显示加盟列表
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/listJoin")
	public ModelAndView listJoin(Page page)throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		page.setPd(pd);
		List<Map<String,Object>> joinList = fruitUserService.listJoins(page);
		mv.setViewName("farm/join/join_list");
		mv.addObject("joinList", joinList);
		mv.addObject("pd", pd);
		mv.addObject("QX",Jurisdiction.getHC());	//按钮权限
		return mv;
	}
	
	/** 查看加盟信息
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/seeMsg")
	public ModelAndView seeMsg(Page page)throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		Map<String,Object> join = fruitUserService.getJoinsMsg(pd);
		mv.setViewName("farm/join/join_see");
		mv.addObject("join", join);
		mv.addObject("pd", pd);
		mv.addObject("QX",Jurisdiction.getHC());	//按钮权限
		return mv;
	}
	
	
	/**显示会员列表
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/listUsers")
	public ModelAndView listFruitUsers(Page page)throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		page.setPd(pd);
		List<Map<String,Object>> fruitUserList = fruitUserService.listUsers(page);	//列出用户列表
		mv.setViewName("farm/user/fruit_user_list");
		mv.addObject("fruitUserList", fruitUserList);
		mv.addObject("pd", pd);
		mv.addObject("QX",Jurisdiction.getHC());	//按钮权限
		return mv;
	}
	
	/**跳转新增用户页面
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/addUser")
	public ModelAndView addUser(Page page)throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		mv.setViewName("farm/user/fruit_user_add");
		mv.addObject("pd", pd);
		mv.addObject("QX",Jurisdiction.getHC());	//按钮权限
		return mv;
	}
	
	/**
	 * 新增会员
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/addMember")
	public ModelAndView addMember(HttpServletRequest requset) throws Exception {
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "add")) {
			return null;
		} // 校验权限
		Map<String, Object> resMap = new HashMap<String, Object>();
		logBefore(logger, Jurisdiction.getUsername() + "新增用户");
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		String phone=pd.getString("phone");
		String pwd=pd.getString("pwd");
		String parentName=pd.getString("parentName");
		UserLogin ul=new UserLogin();
		ul.setParentName(parentName);
		ul.setPhone(phone);
		ul.setPwd(pwd);
		resMap=userService.saveUserPC(ul);
		ResultInfo ru=(ResultInfo)resMap.get("result");
		String state=ru.getState();
		String msg=ru.getMessage();
		if(state=="1"){
			mv.addObject("msg", "注册成功!");
		} else if(state=="0"){
			mv.addObject("msg", msg);
		}
		mv.setViewName("save_result");
		return mv;
	}
	
}
